package org.wzy.design.patterns.prototype.greatestage;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;

// 齐天大圣
public class TheGreatestSage extends Monkey implements Cloneable, Serializable {

	private static final long serialVersionUID = -6129497883112387370L;
	
	private GoldRingStaff staff;
	
	// 从石头缝里蹦出来
	public TheGreatestSage() {
		/**
		 * clone方法不走构造方法！！！
		 */
		System.out.println("-----------------------------------");
		
		this.staff = new GoldRingStaff();
		this.birthday = new Date();
		this.height = 150;
		this.weight = 30;
	}
	
	// 分身技能
	public Object clone() {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		
		ByteArrayInputStream bis = null;
		ObjectInputStream ois = null;
		try {
			// 默认浅克隆，只克隆8种基本数据类型和String
//			return super.clone();
			
			// 序列化
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);
			
			// 反序列化
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			TheGreatestSage sage = (TheGreatestSage) ois.readObject();
			sage.birthday = new Date();
			
			return sage;
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	// 变化
	public void change() {
		TheGreatestSage copySage = (TheGreatestSage) clone();
		System.out.println("大圣本尊生日是：" + this.getBirthday().getTime());
		System.out.println("克隆大圣的生日：" + copySage.getBirthday().getTime());
		System.out.println("大圣本尊和克隆大圣是否为同一个对象：" + (this == copySage));
		System.out.println("大圣本尊持有的金箍棒跟克隆大圣的金箍棒是否为同一个对象：" + (this.getStaff() == copySage.getStaff()));
	}

	public GoldRingStaff getStaff() {
		return staff;
	}

	public void setStaff(GoldRingStaff staff) {
		this.staff = staff;
	}
	
}
